import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { MinioClientService } from './minio-client.service';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class UploadService {
  constructor(
    private readonly minioClientService: MinioClientService,
    private readonly configService: ConfigService,
  ) {}

  async uploadFile(file: Express.Multer.File) {
    try {
      const bucketName = this.configService.get('MINIO_BUCKET');
      // 按照年月生成文件夹
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const fileName = `${year}/${month}/${day}/${Date.now()}-${file.originalname}`;
      // console.log(fileName);

      // 上传文件到 MinIO
      await this.minioClientService.client.putObject(
        bucketName,
        fileName,
        file.buffer,
        file.size,
      );

      // 生成文件访问URL
      const fileUrl = `http://${this.configService.get('MINIO_ENDPOINT')}:${this.configService.get('MINIO_PORT')}/${bucketName}/${fileName}`;

      return {
        url: fileUrl,
        fileName: fileName,
        originalName: file.originalname,
        // 单位为KB
        size: (file.size / 1024).toFixed(2) + 'KB',
        mimeType: file.mimetype,
      };
    } catch (error) {
      throw new HttpException(
        '文件上传失败',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}